<template>
  <div class="tpl-container">
    <div class="mb20 condition-container">
      <div class="condition">
        <span class="color_494949 ft12 pr5 w70">{{ translate('彩屏标识') }}：</span>
        <ElInput
          v-model="UUID"
          class="w164 mr14"
          placeholder="请输入彩屏标识"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5 w70">{{ translate('正反面屏') }}：</span>
        <!-- <ElInput v-model="CSName" class="w164" placeholder="请输入彩屏名称" /> -->
        <el-select v-model="CSName" class="m-2 w164" placeholder="Select">
          <el-option
            v-for="item in csNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5 w70">{{ translate('单双面屏') }}：</span>
        <!-- <ElInput v-model="CSName" class="w164" placeholder="请输入彩屏名称" /> -->
        <el-select v-model="singleValue" class="m-2 w164" placeholder="Select">
          <el-option
            v-for="item in singleName"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5 w70">{{ translate('屏幕类型') }}：</span>
        <el-select v-model="LCDType" class="m-2 w164" placeholder="Select">
          <el-option
            v-for="item in types"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5 w70">{{ translate('商品组合') }}：</span>
        <ElInput
          v-model="MPCode"
          class="w164"
          :placeholder="translate('请输入商品组合')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5 w70">{{ translate('彩屏模板') }}：</span>
        <ElInput
          v-model="CSTypeID"
          class="w164"
          :placeholder="translate('请输入彩屏名称')"
        />
      </div>
      <div class="condition">
        <ElButton class="settingBtn" type="primary" @click="search">
          {{ translate('查询') }}
        </ElButton>
        <!-- <ElButton
          v-if="MenuAuth('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
        >
          新增
        </ElButton> -->
      </div>
    </div>
    <div class="btns">
      <Tabs
        :multiple-selection="multipleSelection"
        @confirm="tabsDialogConfirm"
      />
    </div>
    <div class="table">
      <ElTable
        ref="multipleTableRef"
        v-loading="loading"
        :border="true"
        :data="tableData"
        @selection-change="handleSelectionChange"
      >
        <ElTableColumn type="selection" width="55" />
        <ElTableColumn
          :label="translate('公司')"
          prop="CompanyName"
          width="auto"
        />
        <ElTableColumn :label="translate('彩屏标识')" width="130">
          <template #default="{ row }">
            <div>
              <span class="iconcolor">{{ row.UUID }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.UUID)" />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('内部编码')"
          prop="Code"
          width="auto"
        />
        <ElTableColumn
          :label="translate('组合编码')"
          width="120"
        >
        <template #default="{ row }">
            <div class="CScode">
              <span>{{ row.CSCode }}</span>
            </div>
        </template>
      </ElTableColumn>
        <ElTableColumn :label="translate('单屏/双屏')">
          <template #default="{ row }">
            <div>
              {{
                row.CSCode.length > 10
                  ? translate('双屏页面')
                  : translate('单屏页面')
              }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('正反面')"
          prop="CSName"
          width="auto"
        />
        <ElTableColumn
          :label="translate('彩屏模板')"
          width="130"
        >
        <template #default="{ row }">
            <div class="CScode">
              <span>{{ row.CSTypeID }}</span>
            </div>
          </template>
      </ElTableColumn>
        <ElTableColumn :label="translate('商品组合')" width="auto">
          <template #default="{ row }">
            <div class="tag-div" v-if="row.tags && row.tags.length && row.tags[0] !== ''">
              <el-tag v-for="tag in row.tags" :key="tag" class="tag">
                <span class="tag-span">{{ tag }}</span>
              </el-tag>
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn label="屏幕类型" prop="LCDType" width="auto" /> -->
        <ElTableColumn :label="translate('彩屏图片')" min-width="80">
          <template #default="{ row }">
            <div class="img-container">
              <ElImage
                fit="contain"
                :hide-on-click-modal="true"
                :initial-index="9"
                :preview-src-list="[row.PathImg]"
                :src="row.PathImg+ '?=' + timestamp"
                :z-index="99999"
                :zoom-rate="1.2"
              />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('屏幕类型')">
          <template #default="{ row }">
            <div>
              {{
                row.LCDType == '00'
                  ? '600*1024'
                  : row.LCDType == '03'
                  ? '800*1280'
                  : translate('默认类型')
              }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('显示方式')">
          <template #default="{ row }">
            <div>
              {{ row.OATUpgrade == 0 ? translate('横屏') : translate('竖屏') }}
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn label="WIFI名称" prop="WFSSID" width="auto" /> -->
        <!-- <ElTableColumn label="音量" prop="Volume" width="auto" /> -->
        <!-- <ElTableColumn label="内部码" prop="Code" width="auto" /> -->
        <ElTableColumn :label="translate('显示模式')">
          <template #default="{ row }">
            <div>
              {{
                row.ChangeTemp == '1'
                  ? translate('全屏图片')
                  : row.ChangeTemp == '2'
                  ? translate('视频图片')
                  : row.ChangeTemp == '3'
                  ? translate('图片轮播')
                  : row.ChangeTemp == '4'
                  ? translate('全屏轮播')
                  : row.ChangeTemp == '5'
                  ? translate('全屏视频')
                  : ''
              }}
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn
          :label="translate('用户名')"
          prop="mqtt_server"
          width="auto"
        /> -->
        <!-- <ElTableColumn :label="translate('推送状态')">
          <template #default="{ row }">
            <div>
              {{
                row.SendStatus == 1 ? translate('正常') : translate('未生效')
              }}
            </div>
          </template>
        </ElTableColumn> -->
        <ElTableColumn :label="translate('程序升级')">
          <template #default="{ row }">
            <div>
              {{
                row.AppUpgradeStatus == 0
                  ? translate('待升级')
                  : translate('已发送升级')
              }}
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn label="固件升级" prop="ESLWidth" width="auto" /> -->
        <!-- <ElTableColumn :label="translate('程序升级')">
          <template #default="{ row }">
            <div>
              {{
                row.OATUpgradeStatus == 0
                  ? translate('待升级')
                  : translate('程序升级成功')
              }}
            </div>
          </template>
        </ElTableColumn> -->
        <ElTableColumn :label="translate('在线状态')">
          <template #default="{ row }">
            <div :class="row.Field2 == 1 ? 'color_l' : 'color_red'">
              <vab-icon :icon="row.Field2 == 1 ? 'link-m' : 'link-unlink-m'" />
              {{ row.Field2 == 1 ? translate('已连接') : translate('未连接') }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('操作')">
          <template #default="{ row }">
            <ElButton
              v-if="MenuAuth('edit')"
              size="small"
              plain
              type="primary"
              @click="editFn(row)"
            >
              {{ translate('修改') }}
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
  <editDialog
    :data="csData"
    :title="translate('编辑')"
    :visible="editDialogVisible"
    @close="editHandleClose"
    @confirm="editHandleConfirm"
  />
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { MenuAuth } from '~/src/utils/permission'
  import { getPageData, csedit } from '@/api/mupro'
  import Tabs from './components/tabs.vue'
  import { save } from './components/save'
  import editDialog from './components/editDialog.vue'
  import { translate } from '@/i18n'
  const UUID = ref('')
  const CSName = ref('')
  const MPCode = ref('')
  const CSTypeID = ref('')
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 20,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"UUID","value":${UUID.value},"displayType":"like"}, {"name":"CSName","value":${CSName.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const timestamp = ref(new Date().getTime())
  const LCDType: any = ref('')
  const types: any = ref([
    {
      label: translate('全部类型'),
      value: '',
    },
    {
      label: '600*1024',
      value: '00',
    },
    {
      label: '800*1280',
      value: '03',
    },
  ])
  const singleValue: any = ref('1')
  const singleName = [
    {
      label: translate('全部'),
      value: '1',
    },
    {
      label: translate('单屏页面'),
      value: '2',
    },
    {
      label: translate('双屏页面'),
      value: '3',
    },
  ]
  const csNames = [
    {
      label: translate('全部'),
      value: '',
    },
    {
      label: translate('正面'),
      value: '正面',
    },
    {
      label: translate('反面'),
      value: '反面',
    },
  ]
  const loading = ref(false)

  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const total = ref(0)
  // 获取表格数据
  const gettableData = async () => {
    loading.value = true
    const { data } = await getPageData(searchInfo)
    loading.value = false
    if (singleValue.value === '1') {
      tableData.value = data?.rows || []
    } else if (singleValue.value === '2') {
      if (data?.rows) {
        const singleData = []
        data?.rows.map((item: any) => {
          if (item.CSCode.length <= 10) {
            singleData.push(item)
          }
        })
        tableData.value = singleData
      }
    } else if (singleValue.value === '3') {
      if (data?.rows) {
        const pairData = []
        data?.rows.map((item: any) => {
          if (item.CSCode.length > 10) {
            pairData.push(item)
          }
        })
        tableData.value = pairData
      }
    }
    // tableData.value = data?.rows || []
    const nowTime = new Date().getTime()
    timestamp.value = nowTime
    tableData.value.map((item: any) => {
      item.onlineStatus =
        nowTime - new Date(item.ModifyDate).getTime() <= 60 * 1000
      item.tags = item.Remark.split(',')
    })
    total.value = data?.total || 0
  }
  gettableData()
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }
 //复制彩屏标识
 const copyToClipboard =async (val: any) => {
    if (navigator.clipboard && window.isSecureContext) {
      try {
      console.log(navigator.clipboard)
      console.log(window.isSecureContext)
      await navigator.clipboard.writeText(val)
      ElMessage({
        message:'复制成功',
        type:'success',
      })
      } catch (err) {
        ElMessage({
        message:'复制失败',
        type:'error',
      })
      }

    }else {
      // 创建text area
    const textArea = document.createElement("textarea")
    textArea.value = val
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = "absolute"
    textArea.style.opacity = 0
    textArea.style.left = "-999999px"
    textArea.style.top = "-999999px"
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand("copy") ? res() : rej()
      textArea.remove()
    }).then(() => {
         ElMessage({
          message: "复制成功",
          type: "success",
        })
      }).catch((err) => {
        ElMessage({
          message: "复制失败",
          type: "error",
        })
      })
    }

  }
  const search = () => {
    searchInfo.pageNo = 1
    if (
      UUID.value.trim() !== '' ||
      CSName.value.trim() !== '' ||
      LCDType.value.trim() !== '' ||
      MPCode.value.trim() !== '' ||
      CSTypeID.value.trim() !== ''
    ) {
      const arr = []
      UUID.value.trim() !== '' &&
        arr.push({ name: 'UUID', value: UUID.value, displayType: 'like' })
      CSName.value.trim() !== '' &&
        arr.push({ name: 'CSName', value: CSName.value, displayType: 'like' })
      LCDType.value.trim() !== '' &&
        arr.push({ name: 'LCDType', value: LCDType.value, displayType: 'like' })
      MPCode.value.trim() !== '' &&
        arr.push({ name: 'MPCode', value: MPCode.value, displayType: 'like' })
      CSTypeID.value.trim() !== '' &&
        arr.push({
          name: 'CSTypeID',
          value: CSTypeID.value,
          displayType: 'like',
        })
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.wheres = `[{"name":"UUID","value": '',"displayType":"like"}, {"name":"CSName","value": '',"displayType":"like"}, {"name":"LCDType","value": '',"displayType":"like"}, {"name":"MPCode","value": '',"displayType":"like"}, {"name":"CSTypeID","value": '',"displayType":"like"}]`
    }
    gettableData()
  }
  const multipleSelection = ref<any[]>([])
  const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
  }
  const tabsDialogConfirm = async (
    result: Array<any>,
    type: string,
    multipleSelection: Array<any>
  ) => {
    console.log(result, type, multipleSelection)
    loading.value = true
    const { data, message, code } = await save(result, type, multipleSelection)
    console.log(data)
    loading.value = false
    if (code == '200') {
      ElMessage({
        message: message,
        type: 'success',
      })
    }

    await gettableData()
  }
  // 编辑
  const csData = ref({})
  const editDialogVisible = ref(false)
  const editFn = (row: any) => {
    csData.value = row
    editDialogVisible.value = true
  }
  const editHandleConfirm = async (result: any) => {
    csData.value = result
    // console.log(csData.value)
    await csedit(csData.value)
    editDialogVisible.value = false
    gettableData()
  }
  const editHandleClose = () => {
    editDialogVisible.value = false
  }
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
    }
    .iconcolor {
      color: #409eff;
    }
    .w70 {
      display: inline-block;
      width: 70px;
      text-align: right;
    }
    .color_l {
      color: #67c23a;
    }
    .color_red {
      color: #f56c6c;
    }
    .CScode {
      color: #67c23a;
    }
    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }

    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }

    .condition-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .condition {
        margin-right: 14px;
        margin-bottom: 10px;
      }
    }

    .btns {
      margin-bottom: 10px;
    }

    .tag {
      margin-top: 4px;
    }
  }
  .el-image {
    width: 56px !important;
  }
  .tag-div {
    // display: grid;
    // justify-content: center;
    // align-items: center;
  }
  .tag-span {
    max-width: 68px;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
</style>
